const {BrowserWindow} = require('electron')
const {merge} = require('lodash')
const {appService} = require("../app")

/**
 * 窗口插件
 */
class WindowService {
    constructor() {
        this.windowContentsIdMap = {}
    }

    /**
     * create window
     */
    create(name, opt) {
        const options = merge({
            x: 10,
            y: 10,
            width: 980,
            height: 650,
            webPreferences: {
                contextIsolation: false,
                nodeIntegration: true
            }
        }, opt)
        if (options.center) {
            delete options.x
            delete options.y
        }
        const win = new BrowserWindow(options)
        const winContentsId = win.webContents.id
        win.webContents.on('did-finish-load', () => {
            this.registerWCid(name, winContentsId)
            win.webContents.setZoomFactor(appService.appZoomFactor)
        })
        win.webContents.on('destroyed', () => {
            this.removeWCid(name)
        })
        win.webContents.on('render-process-gone', (event, details) => {
            this.removeWCid(name)
        })
        return win
    }

    /**
     * 获取窗口Contents id
     */
    getWCid(name) {
        return this.windowContentsIdMap[name] || null
    }

    /**
     * 获取主窗口Contents id
     */
    getMWCid() {
        return this.windowContentsIdMap['main'] || null
    }

    /**
     * 注册窗口Contents id
     */
    registerWCid(name, id) {
        this.windowContentsIdMap[name] = id
    }

    /**
     * 销毁窗口Contents id
     */
    removeWCid(name) {
        delete this.windowContentsIdMap[name]
    }
}

WindowService.toString = () => '[class WindowService]'
module.exports = {
    windowService: new WindowService()
}